<?php
/**
 * (exporter)
 */
namespace App\Exporter\Purchase;

use Maatwebsite\Excel\Concerns\FromView;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithProperties;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class ContractExporter implements FromView,WithProperties,WithTitle,ShouldAutoSize,WithColumnWidths,WithStyles
{
    protected $purchase;

    protected $param;

    public function __construct($purchase,$param)
    {
        $this->purchase = $purchase;
        $this->param = $param;
    }

    public function styles(Worksheet $sheet)
    {
        $styleArray = [
            'font' => [
                'size' => 10,
                'name' => 'simsun',
            ],
            'alignment' => [
                'vertical' => Alignment::HORIZONTAL_CENTER,
                'horizontal' => Alignment::HORIZONTAL_LEFT,
            ],
        ];
        $sheet->getStyle('A:H')->applyFromArray($styleArray);

        $sheet->getStyle('A1:H1')->getFont()->setSize(14)->setName('simsun');
        $sheet->getStyle('A1:H1')->getAlignment()
            ->setVertical(Alignment::HORIZONTAL_CENTER)
            ->setHorizontal(Alignment::HORIZONTAL_CENTER);

        $sheet->getStyle('A3:H3')->getBorders()->getTop()->setBorderStyle(Border::BORDER_THIN);
        $sheet->getStyle('A3:H7')->getBorders()->getRight()->setBorderStyle(Border::BORDER_THIN);
        $sheet->getStyle('A7:H7')->getBorders()->getBottom()->setBorderStyle(Border::BORDER_THIN);
        $sheet->getStyle('H3:H7')->getBorders()->getRight()->setBorderStyle(Border::BORDER_THIN);
    }

    public function columnWidths(): array
    {
        return ['A' => 15, 'B' => 30,'C' => 30, 'D' => 15, 'E' => 12, 'F' => 15, 'G' => 15, 'H' => 15];
    }

    public function title(): string
    {
        return '采购合同';
    }

    public function properties(): array
    {
        return [
            'creator'        => '新钱潮科技',
            'title'          => '采购合同',
            'description'    => '采购合同',
            'company'        => '新钱潮科技',
        ];
    }

    public function view(): View
    {
        $purchase = $this->purchase;
        $param = $this->param;
        $orderNum = 0;
        $orderAmount = 0;
        foreach($purchase->order_detail as $item){
            $orderNum += $item->order_num ?: 0;
            $orderAmount += round(($item->unit_price ?:0) * ($item->order_num?:0),3);
        }
        return view('purchase.contract-creat-excel.index', compact('purchase','param','orderNum','orderAmount'));
    }

}
